package cn.serenedream.housedecoration.controller;

import cn.serenedream.housedecoration.dto.UserDTO;
import cn.serenedream.housedecoration.entity.User;
import cn.serenedream.housedecoration.serivce.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    UserService userService;

    @GetMapping("")
    public String list(@RequestParam(value = "current", required = false, defaultValue = "0") Integer currentPage,
                       @RequestParam(value = "page", required = false, defaultValue = "10") Integer pageSize,
                       @RequestParam(value = "name", required = false) String name,
                       Model model,
                       HttpServletRequest httpServletRequest) {
        Page<User> users = null;
        if (name == null) {
            users = userService.list(currentPage, pageSize);
        } else {
            users = userService.findByName(currentPage, pageSize, name);
            model.addAttribute("searchName", name);
        }

        model.addAttribute("users", users);
        model.addAttribute("requestURI", httpServletRequest.getRequestURI());
        return "classify/userInformation";
    }

    @PostMapping("save")
    public String save(@Valid UserDTO userDTO, Model model, BindingResult result) {
        if (result.hasErrors()) {
            model.addAttribute("error", result);
            return "classify/userInformation";
        }

        userService.save(userDTO);
        return "redirect:/user";
    }

    @GetMapping("delete/{id}")
    public String delete(@PathVariable String id) {
        userService.delete(id);
        return "redirect:/user";
    }
}
